package com.et114.core.utility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.et114.core.common.AppContext;

/**
 * @author guanhw
 */
public class ThreadSynchronizer {
	private static Log			logger				= LogFactory.getLog( ThreadSynchronizer.class );
	private static  int	MAX_THREAD_NUM		= AppContext.getFrameWorkPropertiesBean().getDownloadMaxThread() ;
	private static int			currentThreadNum	= 0;
	private static ThreadSynchronizer	ts	= new ThreadSynchronizer();
	
	private ThreadSynchronizer ( ) {
		
	}
	/**
	 * 进入线程控制方法
	 */
	public static void threadEnter ( ) {
		synchronized ( ts ) {
			if  ( currentThreadNum >= MAX_THREAD_NUM ) {
				try {
					log( "sleep..." );
					ts.wait();
				} catch ( InterruptedException e ) {
					e.printStackTrace();
				}
			} ;
			currentThreadNum++;
			log( "running..." );
		}
	}

	/**
	 * 线程退出时的控制方法。
	 */
	public static void threadExit ( ) {
		synchronized ( ts ) {
			currentThreadNum--;
			ts.notifyAll();
			log( "exit..." );
		}
	}

	protected static void log ( String info ) {
		logger.info( "[" + Thread.currentThread().getName() + "] " + info
				+ " (Current Running Thread:" + currentThreadNum + ")" );
		System.out.flush();
	}

	public static void main ( String [ ] args ) {
		for ( int i = 0; i < 20; i++ ) {
			Thread thread = new Thread( new Runnable() {
				public void run ( ) {
					ThreadSynchronizer.threadEnter();
					// Do something that takes a lot of times.
					double c = 2.345;
					for ( int j = 0; j < 10000000; j++ ) {
						c = c * 1.234;
					}
					ThreadSynchronizer.threadExit();
				}
			} );
			thread.setName( "Thread" + i );
			thread.start();
		}
	}
}
